﻿using System.Collections;
using System.Collections.Generic;
using Protocol.Dto.Fight;
using UnityEngine;

namespace Script.Character
{
    public class RightPlayer : CharacterBase
    {
        private void Awake()
        {
            Bind(CharacterEvent.INIT_RIGHT_CARD,
                CharacterEvent.ADD_RIGHT_CARD,
                CharacterEvent.REMOVE_RIGHT_CARD);
        }

        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case CharacterEvent.INIT_RIGHT_CARD:
                    StartCoroutine(InitCardList());
                    break;
                case CharacterEvent.ADD_RIGHT_CARD:
                    AddTableCard();
                    break;
                case CharacterEvent.REMOVE_RIGHT_CARD:
                    RemoveCard(((List<CardDto>) message).Count);
                    break;
            }
        }

        // 卡牌的父物体
        private Transform cardParent;
        private List<GameObject> cardObjList;


        private void Start()
        {
            cardParent = transform.Find("CardPoint");
            cardObjList = new List<GameObject>();
        }

        private IEnumerator InitCardList()
        {
            GameObject cardPrefab = Resources.Load<GameObject>("Card/otherCard");

            for (int i = 0; i < 17; i++)
            {
                CreateGo(i, cardPrefab);

                yield return new WaitForSeconds(0.1f);
            }
        }


        /// <summary>
        /// 创建卡牌游戏物体
        /// </summary>
        /// <param name="index"></param>
        /// <param name="cardPrefab"></param>
        private void CreateGo(int index, GameObject cardPrefab)
        {
            GameObject card = Instantiate(cardPrefab, cardParent);
            card.transform.localPosition = new Vector3(0.15f * index, 0, 0);
            card.GetComponent<SpriteRenderer>().sortingOrder = index;

            cardObjList.Add(card);
        }

        private void AddTableCard()
        {
            GameObject cardPrefab = Resources.Load<GameObject>("Card/otherCard");

            for (int i = 0; i < 3; i++)
            {
                CreateGo(i, cardPrefab);
            }
        }

        /// <summary>
        /// 移除卡牌的游戏的物体
        /// </summary>
        private void RemoveCard(int cardCount)
        {
            for (int i = cardCount; i < cardObjList.Count; i++)
            {
                cardObjList[i].SetActive(false);
            }
        }
    }
}